import os
import sys
import warnings

import pandas as pd

sys.path.append('..')
warnings.filterwarnings('ignore')

from tools.setting import DATA_DIR
from tools.tools import get_all_data, segmented_maxdrawdown_all

ANALYSIS_DATA_DIR = os.path.join(DATA_DIR, 'analysis')
os.makedirs(ANALYSIS_DATA_DIR, exist_ok=True)
DRAWDOWN_ANALYSIS_DATA_DIR = os.path.join(ANALYSIS_DATA_DIR, 'drawdown')
os.makedirs(DRAWDOWN_ANALYSIS_DATA_DIR, exist_ok=True)


def drawdown_ratio():
    # 读取数据，计算价格最大回撤
    df_price, df_amount, df_marketcap = get_all_data()
    df_price_drawdown = segmented_maxdrawdown_all(df_price, ['2020-03-12'])
    df_price_drawdown.to_csv(os.path.join(DRAWDOWN_ANALYSIS_DATA_DIR, 'price_drawdown.csv'))

    marketcap_2017 = df_marketcap.loc['2017-12-01':'2018-01-01', :]
    # 2017年高点市值前50
    marketcap_top50_2017 = marketcap_2017.mean(axis=0).sort_values(ascending=False).index[:50]
    # 2017年高点市值前100
    marketcap_top100_2017 = marketcap_2017.mean(axis=0).sort_values(ascending=False).index[:100]
    # 2017年高点市值前200
    marketcap_top200_2017 = marketcap_2017.mean(axis=0).sort_values(ascending=False).index[:200]

    marketcap_2021 = df_marketcap.loc['2021-02-01':'2021-05-01', :]
    # 2021年高点市值前50
    marketcap_top50_2021 = marketcap_2021.mean(axis=0).sort_values(ascending=False).index[:50]
    # 2021年高点市值前100
    marketcap_top100_2021 = marketcap_2021.mean(axis=0).sort_values(ascending=False).index[:100]
    # 2021年高点市值前200
    marketcap_top200_2021 = marketcap_2021.mean(axis=0).sort_values(ascending=False).index[:200]

    results = []
    _df1 = df_price_drawdown.loc['2017-01-01':'2020-03-12', :]
    _df2 = df_price_drawdown.loc['2020-03-13':, : ]
    for top_num in [50, 100, 200]:
        if top_num == 50:
            coins_list1 = marketcap_top50_2017
            coins_list2 = marketcap_top50_2021
        elif top_num == 100:
            coins_list1 = marketcap_top100_2017
            coins_list2 = marketcap_top100_2021
        else:
            coins_list1 = marketcap_top200_2017
            coins_list2 = marketcap_top200_2021
        for ratio_threshold in [0.7, 0.8, 0.9, 0.95]:
            _df = pd.concat([_df1[coins_list1], _df2[coins_list2]], axis=0)
            _df_filter = _df[_df >= ratio_threshold]
            drawdown_ratio = _df_filter.count(axis=1) / _df.count(axis=1)
            drawdown_ratio.name = f'top{top_num}_coins_drawdown_over_ratio_{ratio_threshold}'
            results.append(drawdown_ratio)

    df = pd.concat(results, axis=1)

    file_name = os.path.join(DRAWDOWN_ANALYSIS_DATA_DIR, f'drawdown_ratio')
    df.to_csv(f'{file_name}.csv')


def volume_maxdrawdown_analysis():
    file_path = os.path.join(DATA_DIR, f'amount_data')

    # 读取数据
    df_btc = pd.read_csv(os.path.join(DATA_DIR, f'ohlcvm_data\\daily\\bitcoin.csv'), index_col='end_date')
    df_btc.sort_index(inplace=True)
    df_eth = pd.read_csv(os.path.join(DATA_DIR, f'ohlcvm_data\\daily\\ethereum.csv'), index_col='end_date')
    df_eth.sort_index(inplace=True)
    df_all_amount = pd.read_csv(os.path.join(file_path, 'total_marketcap_and_amount.csv'), index_col='end_date')
    df_all_amount.sort_index(inplace=True)
    df_binance_btc_amount = pd.read_csv(os.path.join(file_path, 'binance_btc_to_stablecoin_amount.csv'),
                                        index_col='date')
    df_binance_btc_amount.sort_index(inplace=True)
    df_all_cex_amount = pd.read_csv(os.path.join(file_path, 'cex_spot_amount_coingecko.csv'), index_col='date')
    df_all_cex_amount.sort_index(inplace=True)
    df_all_cex_amount['amount'] = df_all_cex_amount.sum(axis=1)

    def inner_drawdown_func(data):
        data['amount_ma7'] = data['amount'].rolling(7).mean()
        data['amount_ma30'] = data['amount'].rolling(30).mean()
        data = data.loc['2017-01-01':, :]
        data['amount_ma30_hwm'] = data['amount_ma30'].expanding().max()
        data['amount_ma30_drawdown'] = (data['amount_ma30'] - data['amount_ma30_hwm']) / data['amount_ma30_hwm']
        return data

    # 计算成交额回撤
    df_btc = inner_drawdown_func(df_btc)
    df_btc.to_csv(os.path.join(DRAWDOWN_ANALYSIS_DATA_DIR, 'btc_amount_analysis.csv'))
    df_eth = inner_drawdown_func(df_eth)
    df_eth.to_csv(os.path.join(DRAWDOWN_ANALYSIS_DATA_DIR, 'eth_amount_analysis.csv'))
    df_all_amount = inner_drawdown_func(df_all_amount)
    df_all_amount.to_csv(os.path.join(DRAWDOWN_ANALYSIS_DATA_DIR, 'all_amount_analysis.csv'))
    df_binance_btc_amount = inner_drawdown_func(df_binance_btc_amount)
    df_binance_btc_amount.to_csv(os.path.join(DRAWDOWN_ANALYSIS_DATA_DIR, 'binance_btc_amount_analysis.csv'))
    df_all_cex_amount = inner_drawdown_func(df_all_cex_amount)
    df_all_cex_amount.to_csv(os.path.join(DRAWDOWN_ANALYSIS_DATA_DIR, 'all_cex_amount_analysis.csv'))


if __name__ == '__main__':
    drawdown_ratio()
    volume_maxdrawdown_analysis()
